<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

use mbilling\BillingBundle\Model\OrdersIpModel;
use mbilling\BillingBundle\Model\UsersAdminLogsModel;
use mbilling\BillingBundle\Model\OrdersVpsModel;
use mbilling\BillingBundle\Entity\ordersIp;
use mbilling\BillingBundle\Entity\usersAdminLogs;

use mbilling\BillingBundle\Form\OrdersIpForm;

class OrdersIpController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $ips = $ip_model->findAll();
        $free_ips = array();
        $notfree_ips = array();
        foreach($ips as $ip)
        {
            if ($ip->getTypeId() != '0')
                array_push($notfree_ips, $ip);
            else
                array_push($free_ips, $ip);
        }
        $ips = array_merge($notfree_ips, $free_ips);
        $error = $this->get('session')->get('synch_ip_error');
        return $this->render('BillingBundle:Orders_ip:index.html.twig', array('ips' => $ips, 'error' => $error));
    }
    public function updateAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $ip = $ip_model->findByPK($id);
        $old_ip = $ip->getIp();
        $old_mac = $ip->getMac();
        //$old_name = $ip->getName();
        $old_type = $ip->getTypeId();
        //$old_owner = $ip->getAccount();
        /*$vps_model = new OrdersVpsModel($em);
        $ordersVps = $vps_model->findAll();
        $ordersVps_string = array();
        $ordersVps_string['0'] = "";
        foreach ($ordersVps as $orderVps)
        {
            $ordersVps_string[$orderVps->getName()] = $orderVps->getName();
        }
        $form = $this->createForm(new OrdersIpForm($ordersVps_string), $ip);*/
        $form = $this->createForm(new OrdersIpForm(), $ip);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                //$ip->setAccount($ordersVps_string[$ip->getAccount()]);
                $new_ip = $form->getData();
                
                if ($new_ip->getTypeId() == '')
                {
                    $new_ip->setName(NULL);
                    $new_ip->setMac(NULL);
                    $new_ip->setAccount(NULL);
                    $new_ip->setForRemove('0');
                    $new_ip->setMessageId(NULL);
                    $jabber = $this->get('jabber');
                    $jabber->sendMessage(39, array('ip' => '"'.$old_ip.'"', 'mac' => '"'.$old_mac.'"'));
                }
                else
                {
                    $jabber = $this->get('jabber');
                    switch ($new_ip->getTypeId())
                    {
                        case 1:
                            $type = 'system';
                        break;
                        case 2:
                            $type = 'vps';
                        break;
                        case 3:
                            $type = 'shared';
                        break;
                        case 4:
                            $type = 'dedicated';
                        break;
                    }
                    if ($old_type == '0')
                    {
                        $jabber->sendMessage(38, array('ip' => '"'.$new_ip->getIp().'"', 'name' => '"'.$new_ip->getName().'"', 'mac' => '"'.$new_ip->getMac().'"', 'type' => '"'.$type.'"', 'owner' => '"'.$new_ip->getAccount().'"'));
                    }
                    else
                    {
                        $jabber->sendMessage(40, array('source' => '"'.$old_ip.' '.$old_mac.'"', 'dest' => '"'.$new_ip->getIp().' '.$new_ip->getName().' '.$new_ip->getMac().' '.$type.' '.$new_ip->getAccount().'"'));
                    }
                }
                $ip_model->create($new_ip);
                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();

                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('12');//страница список ip
                $log->setObjectId($new_ip->getId());//изменяемый объект
                $log->setActionTypeId('2');//изменение ip
                $log_model->create($log);

                return new RedirectResponse($this->generateUrl('orders_ip_show'));
            }
        }
        return $this->render('BillingBundle:Orders_ip:create.html.twig', array('form' => $form->createView(), 'ip' => $ip));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $ip = $ip_model->findByPK($id); 
        
        $jabber = $this->get('jabber');
        $jabber->sendMessage(39, array('ip' => '"'.$ip->getIp().'"', 'mac' => '"'.$ip->getMac().'"'));
        
        $ip->setName(NULL);
        $ip->setMac(NULL);
        $ip->setAccount(NULL);
        $ip->setTypeId('0');
        $ip->setForRemove('0');
        $ip->setMessageId(NULL);
        $ip_model->create($ip);

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $log_model = new UsersAdminLogsModel($em);
        $log = new usersAdminLogs();
        $log->setAdminId($userCurrent->getId());
        $log->setPageId('12');//страница список ip
        $log->setObjectId($id);//изменяемый объект
        $log->setActionTypeId('3');//удаление ip
        $log_model->create($log);
        
        return new RedirectResponse($this->generateUrl('orders_ip_show'));
    }
    public function synchAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $this->get('session')->set('synch_ip_error', '');
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
        {
            $this->get('session')->set('synch_ip_error', 'jabber error');
            return new RedirectResponse($this->generateUrl('orders_ip_show'));
        }
            
        $id = $jabber->sendMessage(37, array());
        $str = $jabber->waitMessage($id); 
        $ips = array();
            
        if (array_key_exists('error', $str))
        {
            $this->get('session')->set('synch_ip_error', $str['error']);
            return new RedirectResponse($this->generateUrl('orders_ip_show'));
        }
        foreach($str as $s)
        {
            $pars = explode("\t", $s);
            if (!array_key_exists($pars['0'], $pars ))
            {
                $ips[$pars['0']] = $pars;
            }
        }
        
        $all_ips = $ip_model->findAll();
        foreach($all_ips as $ip)
        {
            if ( ($ip->getIsActive()) && ($ip->getTypeId() != '0') )
            {
                $ip->setName(NULL);
                $ip->setMac(NULL);
                $ip->setTypeId('0');
                $ip->setAccount(NULL);
                $ip->setForRemove('0');
                $ip->setMessageId(NULL);
                $ip_model->create($ip);
            }
        }
        foreach($ips as $pars)
        {
            $ip = $ip_model->findByIp($pars['0']);
            if (!isset($ip))
                continue;
            $ip->setName($pars['1']);
            $ip->setMac($pars['2']);
            switch($pars['3'])
            {
                case "system":
                    $ip->setTypeId('1');
                break;
                case "vps":
                    $ip->setTypeId('2');
                break;
                case "shared":
                    $ip->setTypeId('3');
                break;
                case "dedicated":
                    $ip->setTypeId('4');
                break;
                default:
                    $ip->setTypeId('0');
            }
            $ip->setAccount($pars['4']);
            $ip_model->create($ip);
        }
        return new RedirectResponse($this->generateUrl('orders_ip_show'));
    }
    public function checkIpHostnameAction($name)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $ip = $ip_model->findByName($name);
        
        if (!isset($ip))
        {
            return new Response('true');
        }
        else
        {
            return new Response('Это имя уже занято');
        }    
    }
    public function checkIpMacAction($mac)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $ip = $ip_model->findByMac($mac);
        
        if (!isset($ip))
        {
            if (preg_match("/[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}:[0-9a-zA-Z]{2}/", $mac))
            {
                return new Response('true');
            }
            else
            {
                return new Response('Неправильный формат');
            }
        }
        else
        {
            return new Response('Этот mac уже занят');
        }    
    }
}